package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Api(tags = "通用接口")
@RequestMapping("/admin/common/upload")
@RestController
public class Upload {
    @Autowired
    private AliOssUtil aliOssUtil;
    @ApiOperation("文件上传")
    @PostMapping
    public Result upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成随机文件名(通过uuid)
        String uuid = UUID.randomUUID().toString();
        String objectName =  uuid + extension;

        try {
            return Result.success(aliOssUtil.upload(file.getBytes(),objectName));
        } catch (IOException e) {
            throw new BaseException(MessageConstant.UPLOAD_FAILED);
        }


    }
}
